package pubsub

import (
	"errors"
	"sync"

	"device-admin/internal/app/grpc/protoc/devicec"
	"device-admin/internal/app/grpc/protoc/robotc"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/helper"
)

var LocalMsgChannelMap sync.Map

// LocalMsgPublish 本机wildmsg命令封装
func LocalMsgPublish(robotID, terminalType, msgType, msgFullName string, msgContent []byte, seq string) (msgID string, err error) {
	if robotID == "" {
		return "", errorx.New("设备id不能为空", -1)
	}

	chanKey := msgType + "@" + robotID + "@" + terminalType
	if seq == "" {
		seq = helper.RandString(16)
	}
	// 95客户端
	if terminalType == "95" {
		sendMsg := &robotc.WildMsg{}
		sendMsg.FromType = robotc.WildMsg_eMobileServiceClient
		sendMsg.FromID = "server"
		sendMsg.ToType = robotc.WildMsg_eMonitorClient
		sendMsg.ToID = "95"
		sendMsg.BodyType = msgFullName
		sendMsg.BodyContent = msgContent
		sendMsg.StrGUID = seq
		if localMsgChannelMapVal, ok := LocalMsgChannelMap.Load(chanKey); ok {
			if localMsgChannel, ok := localMsgChannelMapVal.(chan *robotc.WildMsg); ok {
				if len(localMsgChannel) >= 50 {
					localMsgChannel = make(chan *robotc.WildMsg, 50)
				}
				localMsgChannel <- sendMsg
				LocalMsgChannelMap.Store(chanKey, localMsgChannel)
				return seq, nil
			}
		}
		// 97或98客户端
	} else {
		sendMsg := &devicec.Msg{}
		sendMsg.Ack = 0
		sendMsg.Seq = seq
		sendMsg.Name = msgFullName
		sendMsg.Content = msgContent
		if localMsgChannelMapVal, ok := LocalMsgChannelMap.Load(chanKey); ok {
			if localMsgChannel, ok := localMsgChannelMapVal.(chan *devicec.Msg); ok {
				if len(localMsgChannel) >= 50 {
					localMsgChannel = make(chan *devicec.Msg, 50)
				}
				localMsgChannel <- sendMsg
				LocalMsgChannelMap.Store(chanKey, localMsgChannel)
				return seq, nil
			}
		}
	}
	return seq, errors.New("LocalMsgPublish pack err")
}
